﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Web;
using NLBS.Entity;
using NLBS.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using NLBS.Security;
using NLBS.Web;

namespace NLBS.Install
{
   public class MSSQLInstallProvider:InstallProvider
    {
       public override void InitializeDataBase(string dataSource, string dataName, string userName, string password)
       {
           string conn = string.Format("Data Source={0};Initial Catalog={1};uid={2};password={3}",
           dataSource, dataName, userName, password);
           string sql1 = HttpContext.Current.Server.MapPath("Install/sqlServer/Installation01.sql");
           string sql2 = HttpContext.Current.Server.MapPath("Install/sqlServer/Installation02.sql");
           string sql3 = HttpContext.Current.Server.MapPath("Install/sqlServer/Installation03.sql");

           int timeout = 600;
           NLBS.Utility.SqlHelper.RunSQL(sql1, conn, timeout);
           System.Threading.Thread.Sleep(1000);
           NLBS.Utility.SqlHelper.RunSQL(sql2, conn, timeout);
           System.Threading.Thread.Sleep(1000);
           NLBS.Utility.SqlHelper.RunSQL(sql3, conn, timeout);
       }

       public override void InitBlog(string adminName, string adminPassword, string blogTitle)
        {
            User user = new User();
            user.UserName = adminName;
            user.Password = StringSecurity.StringToSHA1Hash(adminPassword);
            user.Homepage = string.Empty;
            user.Salt = "";
            user.IP = RequestWrapper.IP;
            user.Gender = 0;
            user.GroupID = 1;
            user.HideEmail = true;
            user.Email = "";
            user.LastVisit = DateTime.Now;
            DbProvider.Instance().InsertUser(user);
            Database database = DatabaseFactory.CreateDatabase();
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("update blog_settings set set_value1='{0}' where set_Name='blogTitle';", blogTitle);
            DbCommand dbCommand = database.GetSqlStringCommand(sb.ToString());
            database.ExecuteNonQuery(dbCommand);
            
        }

        public override bool TestCollection(string dataSource, string dataName, string userName, string password)
        {
            string connStr = string.Format("Data Source={0};Initial Catalog={1};uid={2};password={3}",
            dataSource, dataName, userName, password);
            SqlConnection conn = new SqlConnection(connStr);
            try
            {
                conn.Open();
                return true;
            }
            catch (Exception ee)
            {

                throw ee;
                return false;
            }
            return false;
        }
    }
}
